package com.Saenko.GPS;

import java.util.Iterator;


import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;

public class GeneralLocationListener implements LocationListener, GpsStatus.Listener
{
	int countGPSConnect = 0;
	static GPSActivity mainActivity;
	
	private boolean D = false;
	String TAG = ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>GPSActivity - GeneralLocationListener";

	public GeneralLocationListener(GPSActivity activity)
	{
		mainActivity = activity;
	}

	/**
	 * Event raised when a new fix is received.
	 */
	public void onLocationChanged(Location loc)
	{
		try
		{
			if (loc != null)
			{
				if(D) Log.e(TAG, "onLocationChanged");
				mainActivity.currentLatitude = loc.getLatitude();
				mainActivity.currentLongitude = loc.getLongitude();
				mainActivity.DisplayLocationInfo(loc);				
			}

		}
		catch (Exception ex)
		{
			mainActivity.SetStatus(ex.getMessage());
			if(D) Log.e(TAG, "onLocationChanged with err0r "+ex);
		}
	}

	public void onProviderDisabled(String provider)
	{
		if(D) Log.e(TAG, "onProviderDisabled provider = "+provider);
		mainActivity.RestartGpsManagers();
	}

	public void onProviderEnabled(String provider)
	{
		if(D) Log.e(TAG, "onProviderEnabled = "+provider);
		mainActivity.RestartGpsManagers();
	}

	public void onStatusChanged(String provider, int status, Bundle extras)
	{
		if(D) Log.e(TAG, "onStatusChanged");
	}

	public void onGpsStatusChanged(int event)
	{
		switch (event)
		{
			case GpsStatus.GPS_EVENT_FIRST_FIX:
				mainActivity.SetStatus("Fix obtained");
				if(D) Log.e(TAG, "Fix obtained");
				break;

			case GpsStatus.GPS_EVENT_SATELLITE_STATUS:

				GpsStatus status = mainActivity.gpsLocationManager.getGpsStatus(null);

				Iterator<GpsSatellite> it = status.getSatellites().iterator();
				int count = 0;
				while (it.hasNext())
				{
					count++;
					GpsSatellite oSat = (GpsSatellite) it.next();

					//Utilities.LogWarning("LocationActivity - onGpsStatusChange: Satellites:" + oSat.getSnr());
					if(D) Log.e(TAG, "LocationActivity - onGpsStatusChange: Satellites:" + oSat.getSnr());
				}

				mainActivity.SetSatelliteInfo(count);
				break;

			case GpsStatus.GPS_EVENT_STARTED:
				countGPSConnect++;
				mainActivity.SetStatus("GPS Started, waiting for fix = "+countGPSConnect);
				if(D) Log.e(TAG, "GPS Started, waiting for fix = "+countGPSConnect);
				
				break;

			case GpsStatus.GPS_EVENT_STOPPED:
				mainActivity.SetStatus("GPS Stopped");
				if(D) Log.e(TAG, "GPS Stopped");
				break;
		}
	}
}
